package com.situ.mall.admin.interceptor;

import com.situ.mall.common.exception.NoLoginException;
import com.situ.mall.common.util.RequestUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yangkx
 * @create 2023-09-11-14:29
 */
//登录校验拦截器
public class LoginInterceptor implements HandlerInterceptor {

    //进入controller之前
    //此方法返回true就是放行了 false就是拦截了
    //判断是否登录
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从session里面找，看看有没有存上值
        Object o = RequestUtil.getCurrent();

        //o == null 说明没登陆过
        if (o == null){
            //是ajax请求（table小工具解析不了HTML页面）就抛异常，返回401错误码;不是ajax请求就重定向
            if (isAjax(request)){
                throw new NoLoginException();
            }else {
                response.sendRedirect("/admin/login");
            }
            return false;
        //说明登陆过
        }else {
            return true;
        }
    }

    //判断请求是不是ajax请求：是ajax返回true，不是ajax返回false
    private boolean isAjax(HttpServletRequest request){
        //从请求头里面取这个参数的值
        String s = request.getHeader("X-Requested-With");
        //直接用一个写死的值，去比较取到的值，这样可以有效避免空指针异常
        return "XMLHttpRequest".equals(s);
    }


    //controller方法完成后，视图返回渲染之前
//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
//    }

    //整个请求结束后，返回结果给浏览器之前，清理资源
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
//    }


}
